<!-- 班级首页 -->
<template>
    <div class="app-container">
        <el-form :inline="true" :model="searchObj" class="demo-form-inline">
            <el-form-item label="班级名">
                <el-input v-model="searchObj.name" placeholder="班级名"></el-input>
            </el-form-item>
            <el-form-item label="讲师" v-if="!isTeacher()">
                <el-select
                    v-model="searchObj.teacherId"
                    filterable
                    remote
                    clearable
                    reserve-keyword
                    placeholder="老师姓名"
                    :remote-method="remoteMethod"
                    :loading="loading"
                >
                    <el-option
                        v-for="item in teachers"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    >
                        <span style="float: left">
                            <el-tooltip placement="top">
                                <div slot="content">
                                    <el-image
                                        style="width: 150px; height: 150px"
                                        :src="item.avatar"
                                        fit="contain"
                                    ></el-image>
                                </div>
                                <el-avatar :size="30" fit="contain" :src="item.avatar"></el-avatar>
                            </el-tooltip>
                        </span>
                        <span>{{ item.name }}</span>
                        <span
                            style="float: right; color: #8492a6; font-size: 13px"
                        >{{ item.career }}</span>
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="pageClass()">查询</el-button>
                <el-button v-if="isTeacher()" type="success" @click="dialogFormVisible=true">新建班级</el-button>
            </el-form-item>
        </el-form>

        <!--***************************表格数据********************************-->
        <el-table :data="rooms" style="width: 100%">
            <el-table-column type="expand">
                <template slot-scope="props">
                    <el-form label-position="left" inline class="demo-table-expand">
                        <el-form-item label="宣传语">
                            <span v-html="props.row.sign"></span>
                        </el-form-item>
                    </el-form>
                </template>
            </el-table-column>
            <el-table-column label="封面" width="200">
                <template slot-scope="scope">
                    <el-image
                        style="width: 150px; height: 100px"
                        :src="scope.row.cover"
                        fit="contain"
                    ></el-image>
                </template>
            </el-table-column>
            <el-table-column label="班级名" width="180" prop="name"></el-table-column>
            <el-table-column label="进入班级的费用" width="180">
                <template slot-scope="scope">{{scope.row.price +"￥"}}</template>
            </el-table-column>
            <el-table-column label="您的角色" width="180" v-if="isTeacher()">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.role===1">所有权限</el-tag>
                    <el-tag v-if="scope.row.role===2" type="success">管理课程</el-tag>
                    <el-tag v-if="scope.row.role===3" type="warning">管理学员</el-tag>
                    <el-tag v-if="scope.row.role===4" type="info">旁观者</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button
                        size="small"
                        type="primary"
                        v-if="scope.row.role===1"
                        @click="openDialog(scope.row)"
                    >编辑信息</el-button>

                    <el-button
                        size="small"
                        type="info"
                        v-if="scope.row.role===1"
                        @click="openTeacherDrawer(scope.row.id)"
                    >管理讲师</el-button>
                    <el-button
                        size="small"
                        type="success"
                        plain
                        v-if="scope.row.role===1||scope.row.role===2"
                        @click="$router.push({
                        name: 'ClassCourse',
                        params: { 'classId': scope.row.id }
                    })"
                    >管理课程</el-button>
                    <el-button
                        size="small"
                        type="warning"
                        plain
                        v-if="scope.row.role===1||scope.row.role===3"
                        @click="$router.push({
                        name: 'ClassUser',
                        params: { 'classId': scope.row.id }
                    })"
                    >管理学员</el-button>
                    <el-button
                        size="small"
                        type="danger"
                        v-if="scope.row.role===1"
                        @click="deleteClass(scope.row.id)"
                    >删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--******************************修改班级信息对话框*********************-->
        <!-- Form -->
        <el-dialog
            title="编辑班级信息"
            :visible.sync="dialogFormVisible"
            @close="dialogFormVisible=false,room={}"
        >
            <el-form :inline="true" class="demo-form-inline">
                <el-form-item label="班级名称">
                    <el-input v-model="room.name"></el-input>
                </el-form-item>
                <br />
                <el-form-item label="入班价格">
                    <el-input-number
                        v-model="room.price"
                        :precision="2"
                        :step="0.1"
                        :min="0"
                        controls-position="right"
                    ></el-input-number>
                </el-form-item>
                <br />
                <el-form-item label="封面">
                    <el-upload
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                        :action="BASE_API"
                        class="avatar-uploader"
                    >
                        <el-image
                            style="width: 200px; height: 180px"
                            :src="room.cover"
                            fit="contain"
                        >
                            <div slot="error" class="image-slot">
                                <el-image
                                    style="width: 500px; height: 300px"
                                    src="/src/assets/image-not-found.png"
                                    fit="contain"
                                ></el-image>
                            </div>
                        </el-image>
                    </el-upload>
                </el-form-item>
                <el-form-item label="宣传标语">
                    <tinymce v-model="room.sign" :height="300" :width="600" />
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false,room={}">取 消</el-button>
                <el-button type="primary" @click="saveOrUpdateClass()">确 定</el-button>
            </div>
        </el-dialog>

        <!--******************************右侧讲师管理抽屉*******************************-->
        <el-drawer title="管理讲师" :visible.sync="teacherDrawer.drawer" direction="rtl" size="30%">
            <span style="width:80%;color: cadetblue;font-size:15px;font-weight: 700;">添加讲师：</span>
            <el-select
                v-model="teacherDrawer.classTeacherAdd.teacherId"
                filterable
                remote
                clearable
                reserve-keyword
                placeholder="老师姓名"
                :remote-method="remoteMethod"
                :loading="loading"
                style="width:80%"
                size="mini"
                ref="popoveRole"
            >
                <el-option
                    v-for="item in teachers"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                >
                    <span style="float: left">
                        <el-tooltip placement="top">
                            <div slot="content">
                                <el-image
                                    style="width: 150px; height: 150px"
                                    :src="item.avatar"
                                    fit="contain"
                                ></el-image>
                            </div>
                            <el-avatar :size="30" fit="contain" :src="item.avatar"></el-avatar>
                        </el-tooltip>
                    </span>
                    <span>{{ item.name }}</span>
                    <span style="float: center;color: #8492a6; font-size: 13px">{{ item.career }}</span>
                    <span style="float: right;">
                        <el-popover placement="left" title="标题" width="200" trigger="click">
                            <el-select
                                v-model="teacherDrawer.classTeacherAdd.role"
                                placeholder="请选择"
                                @change="addClassTeacher"
                            >
                                <el-option :key="1" label="所有权限" :value="1"></el-option>
                                <el-option :key="2" label="管理课程" :value="2"></el-option>
                                <el-option :key="3" label="管理学员" :value="3"></el-option>
                                <el-option :key="4" label="旁观者" :value="4"></el-option>
                            </el-select>
                            <el-button
                                size="mini"
                                type="primary"
                                plain
                                icon="el-icon-plus"
                                circle
                                slot="reference"
                            ></el-button>
                        </el-popover>
                    </span>
                </el-option>
            </el-select>
            <el-table
                :data="teacherDrawer.teachers.filter(data => !teacherDrawer.search || data.name.toLowerCase().includes(teacherDrawer.search.toLowerCase()))"
                style="width: 100%"
            >
                <el-table-column label="头像" width="80">
                    <template slot-scope="scope">
                        <el-avatar :size="45" fit="fill" :src="scope.row.avatar"></el-avatar>
                    </template>
                </el-table-column>
                <el-table-column label="姓名" prop="name"></el-table-column>
                <el-table-column label="权限">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.role===1">所有权限</el-tag>
                        <el-tag v-if="scope.row.role===2" type="success">管理课程</el-tag>
                        <el-tag v-if="scope.row.role===3" type="warning">管理学员</el-tag>
                        <el-tag v-if="scope.row.role===4" type="info">旁观者</el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="right" width="200">
                    <template slot="header" slot-scope="scope">
                        <el-input v-model="teacherDrawer.search" size="mini" placeholder="输入关键字搜索" />
                    </template>
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            @click="teacherDrawer.deleteClassTeacherdialogVisible = true,teacherDrawer.classTeacherUpdate.id=scope.row.id"
                        >Edit</el-button>
                        <el-button
                            size="mini"
                            type="danger"
                            @click="deleteClassTeacher(scope.row.id)"
                        >Delete</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-drawer>

        <!--******************************修改讲师权限的对话框*******************************-->
        <el-dialog
            title="提示"
            :visible.sync="teacherDrawer.deleteClassTeacherdialogVisible"
            width="30%"
            @close="teacherDrawer.deleteClassTeacherdialogVisible = false,teacherDrawer.classTeacherUpdate={}"
        >
            <el-select v-model="teacherDrawer.classTeacherUpdate.role" placeholder="请选择">
                <el-option :key="1" label="所有权限" :value="1"></el-option>
                <el-option :key="2" label="管理课程" :value="2"></el-option>
                <el-option :key="3" label="管理学员" :value="3"></el-option>
                <el-option :key="4" label="旁观者" :value="4"></el-option>
            </el-select>
            <span slot="footer" class="dialog-footer">
                <el-button
                    @click="teacherDrawer.deleteClassTeacherdialogVisible = false,teacherDrawer.classTeacherUpdate={}"
                >取 消</el-button>
                <el-button type="primary" @click="updateClassTeacher()">确 定</el-button>
            </span>
        </el-dialog>

        <!--******************************分页*******************************-->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
            :current-page="current"
            :hide-on-single-page="true"
            :page-sizes="[6, 15, 20, 30, 40, 50]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        ></el-pagination>
        <!--            :hide-on-single-page="true"-->
        <el-backtop :visibility-height="100"></el-backtop>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import classApi from "@/api/course/classroom";
import { getTeacherByName } from "@/api/ucenter/teacher";
import Tinymce from "@/components/Tinymce";
export default {
    //import引入的组件需要注入到对象中才能使用
    components: { Tinymce },
    data() {
        //这里存放数据
        return {
            searchObj: {},
            teachers: [],
            loading: "",
            //分液器
            current: 1,
            limit: 6,
            total: 0,
            rooms: [],
            room: {},
            dialogFormVisible: false,
            BASE_API: process.env.BASE_API + "/oss/uploadPhoto",
            teacherDrawer: {
                classId: "",
                deleteClassTeacherdialogVisible: false,
                drawer: false,
                teachers: [],
                search: "",
                classTeacherAdd: {},
                classTeacherUpdate: {},
            },
        };
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
        //讲师搜索列表
        remoteMethod(query) {
            if (query !== "") {
                this.loading = true;
                getTeacherByName(query).then((response) => {
                    this.teachers = response.data.teachers;
                    this.loading = false;
                });
            } else {
                this.teachers = [];
            }
        },

        pageClass() {
            return new Promise((resolve) => {
                classApi
                    .pageClass(this.current, this.limit, this.searchObj)
                    .then((response) => {
                        this.rooms = response.data.classrooms;
                        this.total = response.data.rows;
                    });
                resolve();
            });
        },
        handleSizeChange(val) {
            this.current = parseInt((this.current * this.limit) / val);
            this.limit = val;
            this.pageClass();
        },
        handleCurrentChange(val) {
            this.current = val;
            this.pageClass();
        },

        //对话框部分
        openDialog(obj) {
            this.room = obj;
            this.dialogFormVisible = true;
        },
        saveOrUpdateClass() {
            if (this.room.id) {
                classApi.updateClass(this.room).then((response) => {
                    this.room = {};
                    this.pageClass();
                    this.dialogFormVisible = false;
                    this.$message({
                        message: "修改成功",
                        type: "success",
                    });
                });
            } else {
                classApi.addClass(this.room).then((response) => {
                    this.room = {};
                    this.pageClass();
                    this.dialogFormVisible = false;
                    this.$message({
                        message: "添加成功",
                        type: "success",
                    });
                });
            }
        },
        deleteClass(id) {
            this.$confirm("确定要删除吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    classApi.deleteClass(id).then((response) => {
                        this.pageClass();
                        this.$message({
                            type: "success",
                            message: "删除成功!",
                        });
                    });
                })
                .catch(() => {});
        },
        //封面
        handleAvatarSuccess(res, file) {
            this.room.cover = res.data.url;
        },

        beforeAvatarUpload(file) {
            const isJPG =
                file.type === "image/jpeg" ||
                file.type === "image/png" ||
                file.type === "image/jpg";
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error("上传头像图片只能是 JPG 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传头像图片大小不能超过 2MB!");
            }
            return isJPG && isLt2M;
        },

        //右侧讲师抽屉
        openTeacherDrawer(id) {
            classApi.getClassTeacher(id).then((response) => {
                this.teacherDrawer.teachers = response.data.teachers;
                this.teacherDrawer.classId = id;
                this.teacherDrawer.drawer = true;
            });
        },
        addClassTeacher(roleId) {
            this.teacherDrawer.classTeacherAdd.classId =
                this.teacherDrawer.classId;
            this.teacherDrawer.classTeacherAdd.role = roleId;
            classApi
                .addClassTeacher(this.teacherDrawer.classTeacherAdd)
                .then((response) => {
                    classApi
                        .getClassTeacher(this.teacherDrawer.classId)
                        .then((response) => {
                            this.teacherDrawer.teachers =
                                response.data.teachers;
                            this.teacherDrawer.classTeacherAdd = {};
                            this.$refs.popoveRole.focus();
                        });
                });
        },
        deleteClassTeacher(id) {
            this.$confirm("确定要移除该讲师吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    classApi.deleteClassTeacher(id).then((response) => {
                        classApi
                            .getClassTeacher(this.teacherDrawer.classId)
                            .then((response) => {
                                this.teacherDrawer.teachers =
                                    response.data.teachers;
                                this.$message({
                                    type: "success",
                                    message: "删除成功!",
                                });
                            });
                    });
                })
                .catch(() => {});
        },
        updateClassTeacher() {
            classApi
                .updateClassTeacher(this.teacherDrawer.classTeacherUpdate)
                .then((response) => {
                    classApi
                        .getClassTeacher(this.teacherDrawer.classId)
                        .then((response) => {
                            this.teacherDrawer.teachers =
                                response.data.teachers;
                            this.teacherDrawer.deleteClassTeacherdialogVisible = false;
                            this.teacherDrawer.classTeacherUpdate = {};
                        });
                });
        },

        init() {
            this.pageClass();
        },
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
        this.init();
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {}, //生命周期 - 销毁之前
    destroyed() {}, //生命周期 - 销毁完成
    activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发，页面一旦激活就会触发
};
</script>
<style scoped>
.l {
    color: cadetblue;
}
</style>